#include "logger.h"

//先进行静态数据成员的初始化
Logger * Logger::_pInstance = nullptr;
Category * Logger::_root = nullptr;

//将log4cpp的代码逻辑写到构造函数中，为什么呢？
//因为这个实现的是一个单例，构造函数只会被调用一次
//log4cpp的初始化逻辑也只会被调用一次
Logger::Logger(){

    //设置appender，并且关联格式化输出
    PatternLayout * pl1 = new PatternLayout();
    pl1->setConversionPattern("%d %c [%p] %m%n");
    OstreamAppender * ap1 = new OstreamAppender("console", &cout);
    ap1->setLayout(pl1);
    FileAppender * ap2 = new FileAppender("file", "singleton.log");
    PatternLayout * pl2 = new PatternLayout();
    pl2->setConversionPattern("%d %c [%p] %m%n");
    ap2->setLayout(pl2);
    
    Category & root = Category::getRoot();
    root.setPriority(Priority::DEBUG);
    root.addAppender(ap1);
    root.addAppender(ap2);
    _root = &root;
}

Logger::~Logger(){
    //回收log4cpp申请的资源空间
    Category::shutdown();
}
//主要的功能是：保证构造函数只会被执行一次，
//log4cpp的代码的只会初始化一次
Logger * Logger::getInstance(){
    if(_pInstance == nullptr){
        _pInstance = new Logger();
    }
    return _pInstance;
}
//和构造函数里面的new对应的
void Logger::destroy(){
    if(_pInstance){
        delete _pInstance;
        _pInstance = nullptr;
    }
}


void Logger::warn(const char * file, int line, const char * func, const char * msg){
    string content = file + to_string(line) + func + msg;
    _root->warn(content);
}
void Logger::error(const char * file, int line, const char * func, const char * msg){
    string content = file + to_string(line) + func + msg;
    _root->error(content);
}
void Logger::debug(const char * file, int line, const char * func, const char * msg){
    string content = file + to_string(line) + func + msg;
    _root->debug(content);
}
void Logger::info(const char * file, int line, const char * func, const char * msg){
    string content = file + to_string(line) + func + msg;
    _root->info(content);
}
